package com.demo.auth.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import com.demo.auth.common.service.TokenService;
import com.demo.auth.common.service.WeChatService;
import com.demo.auth.domain.wx.AppletLogin;
import com.demo.auth.domain.wx.GetWxWebCode;
import com.demo.common.core.domain.SysUserWxBo;
import com.demo.common.core.result.R;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author MyPC
 */
@Api(tags = "D - 微信授权接口")
@RestController
@RequestMapping("/we-chat")
public class WeChatController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WeChatService weChatService;


    @ApiOperation("微信小程序授权登录")
    @PostMapping("/loginWx")
    public R<SaTokenInfo> loginInfo(@Valid @RequestBody AppletLogin appletLogin) {
        SysUserWxBo sysUserWxBo = weChatService.getLetsWxUserInfoBo(appletLogin);
        return R.ok(tokenService.createToken(weChatService.getLoginUser(sysUserWxBo)));
    }

    @ApiOperation("获取网站登录二维码")
    @PostMapping("/getWxWebCode")
    public R<String> getWxWebCode(@Valid @RequestBody GetWxWebCode getWxWebCode) {
        return R.ok(weChatService.getWxWebCode(getWxWebCode));
    }

    @ApiOperation("web回调地址")
    @GetMapping("/callBackWeb")
    public R<SaTokenInfo> callBack(String code, String state) {
        SysUserWxBo sysUserWxBo = weChatService.getUserWxInfoBo(code, "web");
        return R.ok(tokenService.createToken(weChatService.getLoginUser(sysUserWxBo)));
    }

    @ApiOperation("获取微信公众号登录页")
    @GetMapping("/getWxGzUrl")
    public R<String> getWxGzUrl(String data) {
        return R.ok(weChatService.getWxGzUrl(data));
    }

    @ApiOperation("微信公众平台回调接口")
    @GetMapping("/callBackGz")
    public R<SaTokenInfo> callBackGz(String code, String state) {
        // 用户存在，返回用户数据
        SysUserWxBo sysUserWxBo = weChatService.getUserWxInfoBo(code, "gz");
        return R.ok(tokenService.createToken(weChatService.getLoginUser(sysUserWxBo)));
    }
}
